<?php

namespace StudyBuddy\Controllers;

use StudyBuddy\Responder;
use StudyBuddy\WebPage;
use StudyBuddy\Paginator;
use StudyBuddy\Template\Urhere;
use StudyBuddy\Request;


/**
 * Controller for rendering
 * the "Members" page
 *
 * If request is by Ajax, it returns only the content
 * of the main area, paginated, sorted and with pagination
 * links if necessary
 *
 */
class Badges extends WebPage
{

	protected $layoutID = 1;

	protected $qtab = 'questions';

	protected $oCursor;

	protected $badgesCount;

	protected $Html;
	
	protected $curtab;

	protected function main(){

		$this->init()
		->getCursor()
		->renderHtml();

		$this->setTitle()
		->makeTopTabs()
		->makeBadgesLegen()
		->makeRecentActivites()
		//->makeRecentTags()
		->makeTutorListing()
		->setUsers();
	}


	
	protected function setTitle(){
		$title = 'Badges summary';
		$this->aPageVars['title'] = $title;
		$this->aPageVars['qheader'] = '<h1>'.$title.'</h1>';

		return $this;
	}

	protected function init(){

		$this->sortOrder = array('_id' => 1);

		return $this;
	}


	protected function makeTopTabs(){
                $guest = null;
                if($this->oRegistry->Viewer->isGuest()) {
                    $guest['link_ask'] = '#'; // 13
                    $guest['link_ask_click'] = ' onclick="oSL.getQuickRegForm()"'; //14
                }
		d('cp');
		$tabs = Urhere::factory($this->oRegistry)->get('tplToptabs', $this->qtab, $guest);
		$this->aPageVars['topTabs'] = $tabs;

		return $this;
	}


	protected function getCursor(){
	
		$this->curtab = $this->oRegistry->Request->get('tab', 's', 'all');
		$where = array('type' => $this->curtab);
		
		if($this->curtab == 'all'){
			$this->oCursor = $this->oRegistry->Mongo->BADGES ->find();
		}else{
			$this->oCursor = $this->oRegistry->Mongo->BADGES ->find($where);
		}
		$this->oCursor->sort($this->sortOrder);
		$this->badgesCount = $this->oCursor->count();

		return $this;
	}
	
	protected function makeRecentTags() {

        $aUserTags = $this->oRegistry->Viewer['a_f_t'];
        if (!empty($aUserTags)) {
            $s = $this->getSortedRecentTags($aUserTags);
        } else {
            $s = $this->oRegistry->Cache->get('qrecent');
        }

        $tags = \tplBoxrecent::parse(array('tags' => $s, 'title' => $this->_('Recent Tags')));
        d('cp');
        $this->aPageVars['tags'] = $tags;

        return $this;
    }

    //hoangto tutor listing
    protected function makeTutorListing() {

        $s = $this->getSortedTutors();
        $tutors = \tplTutorBox::parse(array('tutors' => $s, 'title' => $this->_('Tutor Listing')));
        d('cp');
        $this->aPageVars['tutors'] = $tutors;

        return $this;
    }

    //hoangto tutor listing
    protected function makeRecentActivites() {

        $s = $this->getSortedActivities();
        $tutors = \tplActivityBox::parse(array('ractivites' => $s, 'title' => $this->_('Recent activities')));
        d('cp');
        $this->aPageVars['activities'] = $tutors;

        return $this;
    }
    
    protected function getSortedRecentTags(array $aUserTags, $type = 'recent') {

        $limit = 9;
        if ('unanswered' === $type) {
            //$cur = $this->oRegistry->Mongo->UNANSWERED_TAGS->find(array(), array('tag', 'i_count'))->sort(array('i_ts' => -1))->limit($limit);
            $cur = $this->oRegistry->Mongo->UNANSWERED_TAGS->find(array(), array('tag', 'i_count'))->sort(array('i_count' => -1))->limit($limit);
        } else {
            //$cur = $this->oRegistry->Mongo->QUESTION_TAGS->find(array('i_count' => array('$gt' => 0)), array('tag', 'i_count'))->sort(array('i_ts' => -1))->limit($limit);
            $cur = $this->oRegistry->Mongo->QUESTION_TAGS->find(array('i_count' => array('$gt' => 0)), array('tag', 'i_count'))->sort(array('i_count' => -1))->limit($limit);
        }

        d('got ' . $cur->count(true) . ' tag results');
        $aTags = iterator_to_array($cur);

        d('aTags: ' . print_r($aTags, 1));

        if (!empty($aTags)) {
            usort($aTags, function($a, $b) use ($aUserTags) {
                        return (in_array($a['tag'], $aUserTags)) ? -1 : 1;
                    });
        };

        d('$aTags now: ' . print_r($aTags, 1));
        $html = ('unanswered' === $type) ? \tplUnanstags::loop($aTags) : \tplLinktag::loop($aTags);

        d('html recent tags: ' . $html);

        return '<div class="tag"><ul>' . $html . '</ul></div>';
    }

    //hoangto tutor listing loop
    protected function getSortedTutors() {

        $cur = $this->oRegistry->Mongo->USERS->find(array('tmp_role' => 'tutor'))->sort(array('experience' => -1))->limit(9);

        $canTeach = '';

        $func = function(&$a) use($canTeach) {
                    $a['canTeach'] = $canTeach;
                };

        $tutors = \tplTutorListing::loop($cur, true, $func);

        return $tutors;
    }

    //hoangto tutor listing loop
    protected function getSortedActivities() {

        $act_link = '';
        $badges = '';

        $func = function(&$a) use($act_link, $badges) {
                    $a['act_link'] = $act_link;
                    $a['badges'] = $badges;
                };

        $cur = $this->oRegistry->Mongo->ACTIVITIES->find()->sort(array('i_ts' => -1))->limit(5);

        $tutors = \tplActivityList::loop($cur, true, $func);

        return $tutors;
    }
	
	//hoangto tutor listing
	protected function makeBadgesLegen(){

		$this->aPageVars['badges_legend'] = '
			<div id="badge-legend">
				<div class="mb">
					<a class="badge" title="gold badge: awarded rarely" href="/badges/gold"><span class="gold">&#9679;</span>&nbsp;Gold Badge</a>
				</div>
				<p>Gold Badges are rare. You\'ll have to actively work toward these. They\'re something of an accomplishment!</p>
				<div class="mb">
					<a class="badge" title="silver badge: awarded occasionally" href="/badges/silver"><span class="silver">&#9679;</span>&nbsp;Silver Badge</a>
				</div>
				<p>Silver badges are awarded for longer term goals. Silver badges are uncommon, but definitely attainable if you\'re interested.</p>
				<div class="mb">
					<a class="badge" title="bronze badge: awarded frequently" href="/badges/bronze"><span class="bronze">&#9679;</span>&nbsp;Bronze Badge</a>
				</div>
				<p>Bronze badges are awarded for basic use of Study Buddy. They are easy to earn.</p>
			</div>';

		return $this;
	}

	protected function renderHtml(){
		
		$curbronze = '';
		$cursilver = '';
		$curgold = '';
		$curall = '';
		
		switch ($this->curtab) {
			case 'bronze':
				$curbronze = 'class="youarehere"';
				break;
			case 'gold':
				$curgold = 'class="youarehere"';
				break;
			case 'silver':
				$cursilver = 'class="youarehere"';
				break;
			default:
				$curall = 'class="youarehere"';
		}
		
		$this->Html =	'<div class="ctl-ct badgeswrap">
						<h3>Badges</h3>
						<p>
							If your questions and answers are highly voted, your contribution to this Q&A community will be recognized with the variety of badges.
							Below is the list of available badges and number of times each type of badge has been awarded.
						</p>
						<div class="subtabs" id="tabs-type">
							<a title="silver badges" href="/badges/bronze" '.$curbronze.'>bronze</a>
							<a title="silver badges" href="/badges/silver" '.$cursilver.'>silver</a>
							<a title="gold badges" href="/badges/gold" '.$curgold.'>gold</a>
							<a title="all badges" href="/badges" '.$curall.'>all</a>
						</div>
						';
		$this->Html .= '<div style="padding:50px;"><table>';
		
		foreach($this->oCursor as $obj){
			$coll = $this->oRegistry->Mongo->USER_BADGES->find(array('badges' => $obj['b_name']));
			
			$this->Html .=	'<tr>
								<td class="check-cell"></td>
								<td class="badge-cell" width="200px">
									<a class="badge" title="'.$obj['b_desc'].'" href="/badges/'.$obj['id'].'">
									<span class="'.$obj['type'].'">&#9679;</span>&nbsp;'.$obj['b_name'].'</a>
									<span class="item-multiplier">x&nbsp;'.$coll->count().'</span>
								</td>
								<td>'.$obj['b_desc'].'</td>
							</tr>';
		}	
		$this->Html .= '</table></div></div>';

		return $this;
	}


	/**
	 * Adds the content of users block
	 * to page body
	 *
	 * @return object $this
	 */
	protected function setUsers(){
	
		$this->aPageVars['body'] .= $this->Html;

		return $this;
	}

}
